<script setup lang="ts">
import { computed, nextTick, onMounted, onUnmounted, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { storeToRefs } from 'pinia';
import { useChatStore } from '../../stores/chatStore';
import type { Chat } from '../../types';

const chatStore = useChatStore();
const { t } = useI18n();
const { chats: allChats, activeChat, searchQuery } = storeToRefs(chatStore);

const openMenuId = ref<string | null>(null);
const renamingChatId = ref<string | null>(null);
const newChatName = ref<string>('');

// 过滤后的聊天列表
const filteredChats = computed<Chat[]>(() => {
  if (!searchQuery.value) return allChats.value;
  return allChats.value.filter(chat => 
    chat.name.toLowerCase().includes(searchQuery.value.toLowerCase())
  );
});

// 设置当前活动的聊天
function setActiveChat(chatId: string) {
  chatStore.setActiveChat(chatId);
}

// 删除聊天
async function deleteChat(chatId: string, event: Event) {
  event.stopPropagation();
  try {
    const success = await chatStore.deleteChat(chatId);
    if (success) {
      openMenuId.value = null; // 关闭菜单
    } else {
      // 可以添加删除失败的提示
      console.error(t('chat.deleteError'));
    }
  } catch (error) {
    console.error(t('chat.deleteError') + ':', error);
    // 这里可以添加错误提示
  }
}

// 开始重命名
function startRenaming(chatId: string, currentName: string, event: Event) {
  event.stopPropagation();
  renamingChatId.value = chatId;
  newChatName.value = currentName;
  openMenuId.value = null; // 关闭菜单
  // 等待DOM更新后聚焦输入框
  nextTick(() => {
    const input = document.querySelector('.rename-input') as HTMLInputElement;
    if (input) {
      input.focus();
      input.select();
    }
  });
}

// 提交重命名
async function submitRename(event: Event) {
  event.stopPropagation();
  if (!renamingChatId.value || !newChatName.value.trim()) return;
  
  try {
    const success = await chatStore.updateChatTitle(renamingChatId.value, newChatName.value.trim());
    if (success) {
      renamingChatId.value = null; // 退出重命名模式
    } else {
      console.error('重命名失败');
    }
  } catch (error) {
    console.error(t('chat.renameError') + ':', error);
  }
}

// 取消重命名
function cancelRename(event: Event) {
  event.stopPropagation();
  renamingChatId.value = null;
}

// 处理回车和ESC键
function handleRenameKeydown(event: KeyboardEvent) {
  if (event.key === 'Enter') {
    submitRename(event);
  } else if (event.key === 'Escape') {
    cancelRename(event);
  }
}

// 关闭菜单的函数
function closeMenu(event: MouseEvent) {
  // 检查点击是否在菜单外部
  if (!(event.target as HTMLElement).closest('.menu-trigger, .menu-content')) {
    openMenuId.value = null;
  }
}

onMounted(async () => {
  await chatStore.fetchChats();
  // 添加全局点击事件监听器
  document.addEventListener('click', closeMenu);
});

// 在组件卸载时移除事件监听器
onUnmounted(() => {
  document.removeEventListener('click', closeMenu);
});
</script>

<template>
  <div class="chat-list">
    <div v-if="filteredChats.length === 0" class="empty-state">
      <div class="empty-icon">💬</div>
      <p>暂无对话历史</p>
    </div>
    
    <div 
      v-for="chat in filteredChats" 
      :key="chat.id"
      class="chat-item"
      :class="{ 'active': chat.id === activeChat }"
      @click="setActiveChat(chat.id)"
    >
      <div class="chat-avatar">
        <div class="avatar-bg">
          <span class="avatar-text">{{ chat.name.charAt(0) }}</span>
        </div>
      </div>
      
      <div class="chat-content">
        <div class="chat-header">
          <template v-if="renamingChatId === chat.id">
            <input
              type="text"
              v-model="newChatName"
              class="rename-input"
              @click.stop
              @keydown="handleRenameKeydown"
              @blur="submitRename($event)"
            >
          </template>
          <span v-else class="chat-name">{{ chat.name }}</span>
        </div>
      </div>
      
              <div class="chat-actions">
                <button 
                  class="action-button rename-btn"
                  @click.stop="startRenaming(chat.id, chat.name, $event)"
                  title="重命名"
                >
                  <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                    <path d="M12 20h9"></path>
                    <path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"></path>
                  </svg>
                </button>
                <button 
                  class="action-button delete-btn"
                  @click.stop="deleteChat(chat.id, $event)"
                  title="删除对话"
                >
                  <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                    <path d="M3 6h18"></path>
                    <path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"></path>
                    <path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"></path>
                  </svg>
                </button>
              </div>
    </div>
  </div>
</template>

<style scoped>
.chat-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
  overflow-y: auto;
  flex: 1;
  max-height: 100%; /* 确保不会超出容器 */
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  text-align: center;
  color: #a0aec0;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
  opacity: 0.5;
}

.empty-state p {
  margin: 0;
  font-size: 14px;
}

.chat-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 12px;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.2s ease;
  position: relative;
  background: rgba(255, 255, 255, 0.5);
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.chat-item:hover {
  background: rgba(255, 255, 255, 0.8);
  border-color: rgba(102, 126, 234, 0.2);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.chat-item.active {
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%);
  border-color: rgba(102, 126, 234, 0.3);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2);
}

.chat-avatar {
  flex-shrink: 0;
  margin-top: 2px;
}

.avatar-bg {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
  position: relative;
}

.avatar-text {
  color: white;
  font-weight: 600;
  font-size: 18px;
  line-height: 1;
  position: relative;
  z-index: 1;
}

.avatar-bg::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.2) 0%, rgba(255, 255, 255, 0) 100%);
  border-radius: 50%;
}

.chat-content {
  flex: 1;
  min-width: 0;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.chat-name {
  font-weight: 600;
  color: #2d3748;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-size: 14px;
}

.chat-time {
  font-size: 12px;
  color: #a0aec0;
  flex-shrink: 0;
  margin-left: 8px;
}

.chat-preview {
  font-size: 13px;
  color: #718096;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.chat-actions {
  display: flex;
  gap: 8px;
  flex-shrink: 0;
  opacity: 0;
  transition: opacity 0.2s ease;
}

.chat-item:hover .chat-actions {
  opacity: 1;
}

.action-button {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 28px;
  height: 28px;
  border-radius: 50%;
  cursor: pointer;
  color: #a0aec0;
  transition: all 0.2s;
  background: transparent;
  border: none;
  padding: 0;
}

.action-button:hover {
  background-color: rgba(102, 126, 234, 0.1);
  color: #667eea;
}

.action-button.delete-btn:hover {
  background-color: rgba(239, 68, 68, 0.1);
  color: #ef4444;
}

/* 重命名输入框样式 */
.rename-input {
  width: 100%;
  padding: 2px 6px;
  border: 1px solid #667eea;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 600;
  color: #2d3748;
  background-color: white;
  transition: border-color 0.2s;
  outline: none;
}

.rename-input:focus {
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
}

/* 自定义滚动条样式 */
.chat-list::-webkit-scrollbar {
  width: 4px;
}

.chat-list::-webkit-scrollbar-track {
  background: transparent;
}

.chat-list::-webkit-scrollbar-thumb {
  background-color: rgba(0, 0, 0, 0.2);
  border-radius: 2px;
}

.chat-list::-webkit-scrollbar-thumb:hover {
  background-color: rgba(0, 0, 0, 0.3);
}
</style>